<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <div class="filter-wrapper">
      <NewPageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
        :filter-btn="filterInfo.btn"
      >
        <template v-slot:filter-operateTime>
          <el-date-picker
            v-model="operateTime"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="datetimerange"
            range-separator="至"
            align="right"
            start-placeholder="操作时间开始日期"
            end-placeholder="操作时间结束日期"
            :clearable="false"
            @change="timeChange"
          ></el-date-picker>
        </template>
      </NewPageFilter>
    </div>
    <div class="filter-wrapper">
      <NewPageFilter :filter-btn="filterInfo.btnList"> </NewPageFilter>
    </div>
    <!-- 表格 -->
    <TableContainer
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :query="filterInfo.query"
      :tab-index="true"
      :field-list="tableInfo.fieldList"
      :pager="true"
      :checkBox="false"
      :handle="tableInfo.handle"
    >
      <template v-slot:col-title="scope">
        <span class="slip-edit" @click="showDetail(scope.row)">{{
          scope.row.title
        }}</span>
      </template>
    </TableContainer>
    <!-- S 上传弹窗 -->
    <UploadDialog
      v-if="uploadOpen"
      :open="uploadOpen"
      :resStatus="resStatus"
      :uploadError="uploadError"
      :uploadSetting="uploadSetting"
      :fileCate="fileCate"
      @submit="submit"
      @close="uploadClose"
    ></UploadDialog>
    <!-- E 上传弹窗 -->
    <!-- S 编辑弹窗 -->
    <EditDialog
      v-if="editOpen"
      :open="editOpen"
      :fileObj="file"
      :uploadSetting="uploadSetting"
      :fileCate="fileCate"
      @submit="submit"
      @close="editClose"
    ></EditDialog>
    <!-- E 编辑弹窗 -->
  </div>
</template>

<script setup name="uploadFile">
import { baseData } from '../index.js'
import UploadDialog from './uploadDialog.vue'
import EditDialog from './editDialog.vue'
import {
  getCategoryListSelect,
  getMyUploadList,
  addUpload,
  removeUpload,
  uploadFile,
  editFile,
  unUpload,
} from '@/api/fileManager'
import { handleTree } from '@/utils/index.js'
import moment from 'moment'
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
let uploadOpen = ref(false)
let editOpen = ref(false)
const uploadSetting = reactive(baseData.uploadSetting)
const ids = ref([])
// table组件-编辑方法
const file = ref({})
const resStatus = ref(true)
const uploadError = ref('')
const fileCate = ref([])
const operateTime = ref([
  moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 30)).format(
    'YYYY-MM-DD'
  ),
  moment(new Date()).format('YYYY-MM-DD'),
])
// 过滤相关配置
const filterInfo = ref({
  query: {
    startDate: operateTime.value[0],
    endDate: operateTime.value[1],
    /* orderBy: 'sfd.cancel_date',
    orderDirect: 'desc', */
  },
  copyQuery: {},
  list: [
    {
      componentType: 'input',
      label: '文档名称/文档编码',
      value: 'searchValue',
      event: search,
    },
    {
      slot: true,
      label: '起止日期',
      value: 'operateTime',
      event: search,
    },
    {
      componentType: 'treeSelect',
      label: '文档目录',
      value: 'fileCategoryId',
      objMap: {
        value: 'id',
        label: 'categoryName',
        children: 'children',
      },
      selectData: [],
    },
    {
      label: '状态',
      value: 'status',
      asValue: 'status',
      componentType: 'select-model',
      code: 'file_status',
    },
    /* {
      componentType: 'select-user',
      label: '作废人',
      value: 'cancelUserName',
      asValue: 'cancelUser',
      highlightRow: true,
      checkBox: false,
    }, */
  ],
  btn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '上传',
      event: upload,
      show: proxy.$permission('uploadFile:upload'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: getMyUploadList,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '文档目录',
      value: 'fileCategoryName',
    },
    {
      label: '文档名称',
      value: 'title',
      type: 'slot',
    },
    {
      label: '文档编码',
      value: 'fileCode',
    },
    {
      label: '上传时间',
      value: 'uploadTime',
    },
    {
      label: '上传人',
      value: 'uploadUserName',
    },
    {
      label: '上传进度',
      value: 'uploadProgressName',
    },
    {
      label: '状态',
      value: 'statusText',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    btList: [
      {
        label: '提交',
        event: publish,
        show: proxy.$permission('uploadFile:submit'),
        ifRender: function (item) {
          // 已提交或者是上传中、上传失败不显示提交按钮
          if (
            item.status !== 'PEND_SUBMIT' ||
            item.uploadProgress === '0' ||
            item.uploadProgress === '-1'
          ) {
            return false
          }
          return true
        },
      },
      {
        label: '取消',
        event: unpublish,
        show: proxy.$permission('uploadFile:unsubmit'),
        ifRender: function (item) {
          if (item.status === 'PEND_PUBLISH' && item.uploadProgress === '1') {
            return true
          }
          return false
        },
      },
      {
        label: '编辑',
        event: edit,
        show: proxy.$permission('uploadFile:edit'),
        ifRender: function (item) {
          // 已提交或者上传失败不显示编辑按钮
          if (item.status !== 'PEND_SUBMIT' || item.uploadProgress === '-1') {
            return false
          }
          return true
        },
      },
      {
        label: '删除',
        event: del,
        show: proxy.$permission('uploadFile:del'),
        ifRender: function (item) {
          // 已提交不显示删除按钮
          if (item.status !== 'PEND_SUBMIT') {
            return false
          }
          return true
        },
      },
    ],
  },
})

onMounted(() => {
  filterInfo.value.copyQuery = proxy.$fn.deepClone(filterInfo.value.query)
})

function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.startDate = val[0]
    filterInfo.value.query.endDate = val[1]
  } else {
    filterInfo.value.query.startDate = ''
    filterInfo.value.query.endDate = ''
  }
  search()
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
function clearSearch() {
  filterInfo.value.query = proxy.$fn.deepClone(filterInfo.value.copyQuery)
  operateTime.value = [
    filterInfo.value.query.startDate,
    filterInfo.value.query.endDate,
  ]
  search()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function submit(data) {
  if (data.id) {
    // 编辑
    editFile(data).then((res) => {
      if (res.code === 200 && res.success) {
        editOpen.value = false
        getList()
      }
    })
  } else {
    // 新增
    uploadFile(data)
      .then((res) => {
        if (res.code === 200 && res.success) {
          resStatus.value = true
          getList()
        } else {
          uploadError.value = res.msg
          resStatus.value = false
        }
      })
      .catch((err) => {
        uploadError.value = '未知错误'
        resStatus.value = false
      })
  }
}
function editClose() {
  editOpen.value = false
  router.replace(route.path) //清空地址栏参数
}
function upload() {
  uploadOpen.value = true
}
function publish(item) {
  const params = {
    id: item.id,
  }
  proxy
    .$confirm('是否提交文档名为"' + item.title + '"的数据项？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(function () {
      return addUpload(params)
    })
    .then((res) => {
      if (res.success) {
        getList()
        proxy.$message.success({
          message: '提交成功',
          showClose: true,
          duration: 3500,
        })
      }
    })
    .catch(() => {})
}
function unpublish(item) {
  proxy
    .$confirm('是否取消文档名为"' + item.title + '"的数据项？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(function () {
      return unUpload(item.id)
    })
    .then((res) => {
      if (res.success) {
        getList()
        proxy.$message.success({
          message: '提交成功',
          showClose: true,
          duration: 3500,
        })
      }
    })
    .catch(() => {})
}
function uploadClose() {
  uploadOpen.value = false
}
// 待提交-待审核-待发布到uploadFileView页面
function setPath(obj) {
  let path = ''
  let _obj = obj
  if (obj.val) {
    _obj = obj.val
  }
  if (
    _obj.status === 'PEND_SUBMIT' ||
    _obj.status === 'PEND_CHECK' ||
    _obj.status === 'PEND_PUBLISH'
  ) {
    path = '/fileManager/uploadFileView/'
  } else {
    path = '/fileManager/fileView/'
  }
  return path
}
// 跳转至文档演示页面
function showDetail(obj) {
  if (obj.status === 'CANCEL') {
    proxy.$message.warning('文档已作废！')
    return
  }
  let path = setPath(obj)
  let active = '/fileManager/upload'
  if (obj.val) {
    if (obj.key === 'title') {
      router.push({
        path: path + obj.val.id,
        query: {
          active,
          id: obj.val.id,
        },
      })
    } else {
      //点击进度失败重传
      if (obj.val.uploadProgress !== '-1') {
        return
      }
      file.value = obj.val
      editOpen.value = true
    }
  } else {
    console.log(path + obj.id)
    router.push({
      path: path + obj.id,
      query: {
        active,
        id: obj.id,
      },
    })
  }

  /*  router.push({
    path: '/fileManager/uploadFileView',
    query: {
      id: obj.val ? obj.val.id : obj.id,
      mainId: obj.mainId ? obj.val.mainId : obj.mainId,
    },
  }) */
}
function edit(obj) {
  file.value = obj
  editOpen.value = true
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
}
function details(row) {
  router.push({
    path: '/fileManager/fileview/' + row.id,
    query: {
      mainId: row.mainId,
      view: 1,
      type: 'view',
    },
  })
}
// table组件-删除方法
function del(row) {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      removeUpload(row.id).then(() => {
        getList()
        proxy.$message.success({
          message: '删除成功',
          showClose: true,
          duration: 3500,
        })
      })
    })
}
function _getCategoryListSelect() {
  getCategoryListSelect({
    includeStop: false,
  }).then((res) => {
    const selectData = res.data
    fileCate.value = selectData
    filterInfo.value.list.forEach((item, index) => {
      if (item.value === 'fileCategoryId') {
        let treeArr = handleTree(selectData, 'id')
        item.selectData = treeArr
      }
    })
  })
}
_getCategoryListSelect()
</script>
